#pragma once

#include <string>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>

using namespace std;

struct user
{

    user(const string &ip, const uint16_t port)
        : _ip(ip), _port(port)
    {
    }

    string _ip;
    uint16_t _port;
};

class onlineUser
{
public:
    onlineUser()
    {
    }

    // 添加上线用户
    void addUser(const string &ip, const uint16_t port)
    {
        string id = ip + "-" + to_string(port);
        users.insert(make_pair(id, user(ip, port)));
    }

    // 用户下线，删除
    void delUser(const string &ip, const uint16_t port)
    {
        string id = ip + "-" + to_string(port);
        users.erase(id);
    }

    // 判断是否在线
    bool isOL(const string &ip, const uint16_t port)
    {
        string id = ip + "-" + to_string(port);
        return users.find(id) != users.end();
    }

    // 广播消息
    void broadcastMessage(int sockfd, const string &ip, const uint16_t port, const string &message)
    {
        for (auto &it : users)
        {
            struct sockaddr_in client;
            client.sin_family = AF_INET;
            client.sin_port = htons(it.second._port);
            client.sin_addr.s_addr = inet_addr(it.second._ip.c_str());

            string responce = ip + "-" + to_string(port) + "# " + message;
            sendto(sockfd, responce.c_str(), responce.size(), 0, (struct sockaddr *)&client, sizeof(client));
        }
    }

private:
    unordered_map<string, user> users;
};